package com.kun.demo04_synchronize.probelm;


import org.junit.Test;

//死锁问题
public class DeadLock {

    static class Mirror{

    }

    static class Lipstick{

    }

    static class MakeUp implements Runnable {

        private Mirror mirror;
        private Lipstick lipstick;

        public MakeUp(Mirror mirror, Lipstick lipstick) {
            this.mirror = mirror;
            this.lipstick = lipstick;
        }

        @Override
        public void run() {
            if (Thread.currentThread().getName().equals("boy1")) {
                makeup(0);
            } else {
                makeup(1);
            }
        }

        public void makeup(int choice) {
            if (choice == 0) {
                synchronized (mirror) {
                    System.out.println(Thread.currentThread().getName() + "正在使用镜子");
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    synchronized (lipstick) {
                        System.out.println(Thread.currentThread().getName() + "正在使用口红");
                    }
                }
            } else {
                synchronized (lipstick) {
                    System.out.println(Thread.currentThread().getName() + "正在使用口红");
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    synchronized (mirror) {
                        System.out.println(Thread.currentThread().getName() + "正在使用口红");

                    }
                }

            }
        }

        public static void main(String[] args) throws InterruptedException {
            Mirror mirror = new Mirror();
            Lipstick lipstick = new Lipstick();
            MakeUp makeup = new MakeUp(mirror, lipstick);
            Thread t1 = new Thread(makeup, "boy1");
            Thread t2 = new Thread(makeup, "boy2");
            t1.start();
            t2.start();

            Thread.sleep(10_000);
        }


    }
}
